<template>
    <div class="write-bus-card">
        <top-nav :title="title"></top-nav>
        <card-dom 
        ref="cardDom"
        :isShow="true"
        :showDomType="'normal'"
        :type="showDomContentType"
        :optionWriteList="optionWriteList"
        :customList="selectOption.custom.list"
        :isShowQrcode="selectOptionActive === 'normal'"
        :isShowCardDom="true"
        :userInfoData="userInfo"/>
        <selec-option 
        :userInfoData="userInfo"
        :selectOption="selectOption" 
        :selectOptionActive="selectOptionActive" 
        :optionWriteList="optionWriteList"
        :customList="selectOption.custom.list"
        @setSelctOption="setSelctOption"
        @setIsShow="setIsShow"
        @changeCustomText="changeCustomText"
        @showDefaultText="showDefaultText"
        ></selec-option>
        <btn-menu @saveCard="saveCard"></btn-menu>
    </div>
</template>

<script>
// 自定义组件
import TopNav from "_components/project/common/TopNav"
import CardDom from "_components/project/common/CardDom"
import SelecOption from "_components/project/WriteBusCard/SelecOption"
import BtnMenu from "_components/project/WriteBusCard/BtnMenu"

// 自定义方法
import { getUserBusInfo, setBusCardTemp } from '_network/request'
import { failTextVantToa, loadingVantToa, clearVantToa } from "_projectFn/prompt"
import { isLoginChose } from '_projectFn/login'
import { checkDataEqualVal } from "_commonFn/check"
import { defaultShare } from "_commonFn/share"
import { getCookie } from '_commonFn/cookie'
import { getProImg } from "_projectFn/images"
import { getText } from "_commonFn/string"
import { getQueryStrParams } from "_commonFn/url"

// 本地图片
import manSexIcon from "_assets/img/sex-man-icon.svg"
import womenSexIcon from "_assets/img/sex-women-icon.svg"

export default {
    name: 'WriteBusCard',
    data() {
        return {
            title: '设置名片内容',
            selectedData: {},
            userInfo: {
                id: "",
				img: "",
				name: "",
				sexImg: "",
				isFollow: 0,
				area: "",
				companyName: "",
				cardA: "",
				cardB: "",
				supply: "", // string	我的供应
				demand: "", // string	我的需求
				findWho: "", //	string	我要找谁
				myHelp: "", // string	我能帮助
				isPartner: "", //int	是否选择了我要找业务互助合作伙伴（1：是，0：否）
				yourSelf: "", // string	介绍自己
				fansCount: "", // 粉丝数量
				isViewWechat: "", // 当前登录用户查看微信权限是否受限(0:否,1:是，-1：未知)
				isUserBusiness: "", // 查看用户是否填写了业务信息(0:否,1:是)
				isMyWx: "", // 查看用户是否具有查看我的微信权限(0:否,1:是)
				isPayViewWx: "", //	int	当前登录用户是否已支付查看过该微信(0:否,1:是)
				viewFreeWx: "", // int	当前登录用户当天免费查看我的微信次数
				maxViewFreeWx: "", // int	每个用户当天免费查看我的微信最大次数
				viewFreeWxPay: "", // float	查看用户查看我的微信支付积分
				getData: {},
				userLevel: "", // int	用户级别(0：普通用户,1:高级用户,2:资深用户,3:超级用户)
				signature: "", // string	用户签名
                offer: "", // Decimal	用户当前总贡献分
                tempImg: '',
                sex: '',
                userId: '',
            },
            queryStr: {},
            selectOption: {
                'normal': {
                    name: '标准样式',
                    id: 'normal',
                    list: []
                },
                'custom': {
                    name: '极简样式',
                    id: 'custom',
                    list: []
                },
            },
            selectOptionActive: 'normal',
            showDomContentType: 'normal', // 名片类型
            optionWriteList: [],
            defaultTemaplateText: [],
        }
    },
    methods: {
        showDefaultText() {
            this.setTempCusData(this.defaultTemaplateText)
        },
        getUserBus() { // 获取用的名片信息
            if (isLoginChose()) {
                loadingVantToa({})
                getUserBusInfo({
                    userId: getCookie("UserId"),
                })
                .then(res => {
                    console.log('获取用的名片信息 res：', res)
                    if (res.errcode == 0) {
                        clearVantToa()
                        this.setUserInfo(res.data)
                        this.setWriteOptionList()
                    } else {
                        if (res.errcode != -2 && res.errCode != 1100) {
                            failTextVantToa()
                        } else {
                            clearVantToa()
                        }
                    }
                }, res => {
                    console.log('fail: res', res)
                    if (res.errcode != 2000) {
                        failTextVantToa()
                    }
                })
                .catch(res => {
                    console.log('catch：res', res)
                    failTextVantToa()
                })
            }
        },
		// 设置用户业务信息
		setUserInfo(data) {
			this.userInfo.getData = data;
			this.userInfo.id = data.UserItem.UserId;
			this.userInfo.userId = data.UserItem.UserId;
			this.userInfo.img = data.UserItem.HeadImg;
            this.userInfo.name = data.UserItem.NickName;
            this.userInfo.sex = data.UserItem.Sex
			this.userInfo.sexImg = data.UserItem.Sex ? getProImg("sex-man-icon.svg", manSexIcon) : getProImg("sex-women-icon.svg", womenSexIcon);
			this.userInfo.isFollow = data.IsFuns;
			this.userInfo.area = data.Area;
			this.userInfo.companyName = data.Company;
			this.userInfo.cardA = data.CardA;
			this.userInfo.cardB = data.CardB;
			this.userInfo.supply = data.Supply; // string	我的供应
			this.userInfo.demand = data.Demand; // string	我的需求
			this.userInfo.findWho = data.FindWho; //	string	我要找谁
			this.userInfo.myHelp = data.MyHelp; // string	我能帮助
			this.userInfo.isPartner = data.IsPartner; //int	是否选择了我要找业务互助合作伙伴（1：是，0：否）
			this.userInfo.yourSelf = data.YourSelf; // string	介绍自己
			this.userInfo.fansCount = data.FansCount; // 粉丝数量
			this.userInfo.isViewWechat = data.IsViewWechat; // 当前登录用户查看微信权限是否受限(0:否,1:是，-1：未知)
			this.userInfo.isUserBusiness = data.IsUserBusiness; // 查看用户是否填写了业务信息(0:否,1:是)
			this.userInfo.isMyWx = data.IsMyWx; // 查看用户是否具有查看我的微信权限(0:否,1:是)
			this.userInfo.isPayViewWx = data.IsPayViewWx; //	int	当前登录用户是否已支付查看过该微信(0:否,1:是)
			this.userInfo.viewFreeWx = data.ViewFreeWx; // int	当前登录用户当天免费查看我的微信次数
			this.userInfo.maxViewFreeWx = data.MaxViewFreeWx; // int	每个用户当天免费查看我的微信最大次数
			this.userInfo.viewFreeWxPay = data.ViewFreeWxPay; // float	查看用户查看我的微信支付积分
			this.userInfo.userLevel = data.UserItem.UserLevel; // int	用户级别(0：普通用户,1:高级用户,2:资深用户,3:超级用户)
			this.userInfo.signature = data.UserItem.Signature; // string	用户签名
            this.userInfo.offer = data.UserItem.Offer; // Decimal	用户当前总贡献分
            const writeBusCardWriteData = JSON.parse(sessionStorage.getItem('WriteBusCardWriteData'))
            this.defaultTemaplateText = writeBusCardWriteData.customTxtItem
            // console.log('cache writeBusCardWriteData', writeBusCardWriteData)
            // console.log('data.UserDefaultTemplateItem', data.UserDefaultTemplateItem)
            if (data.UserDefaultTemplateItem && data.UserDefaultTemplateItem.DefaultTxt && data.UserDefaultTemplateItem.DefaultTxt.length > 0) {
                if (data.UserDefaultTemplateItem.SetType == 2) {
                    this.selectOptionActive = 'custom'
                    this.showDomContentType = 'custom'
                } else {
                    this.selectOptionActive = 'normal'
                    this.showDomContentType = 'normal'
                }
                // 选择的不是设置的模板
                if (data.UserDefaultTemplateItem.TplNo != writeBusCardWriteData.tplNo) {
                    // console.log('已设置的模板与选择的不一致，优先显示选择的模板')
                    this.setTempCusData(writeBusCardWriteData.customTxtItem)
                } else {
                    this.setTempCusData(data.UserDefaultTemplateItem.DefaultTxt)
                }
            } else {
                if (Array.isArray(writeBusCardWriteData.customTxtItem) && writeBusCardWriteData.customTxtItem.length > 0) {
                    this.setTempCusData(writeBusCardWriteData.customTxtItem)
                }
            }
        },
        setTempCusData(data) {
            // console.log('setTempCusData', data)
            const that = this
            that.selectOption.custom.list = []
            data.forEach(item => {
                if (item.CustomTxt) {
                    that.selectOption.custom.list.push(item.CustomTxt)
                }
            })
            // console.log('list', that.selectOption.custom.list)
        },
        getViewProject() {
            if (this.selectOptionActive === 'normal') {
                // console.log('this.optionWriteList', this.optionWriteList)
                const viewProjectObj = {
                    area: 1,
                    company: 2,
                    presentation: 3,
                    supply: 4,
                    demand: 5,
                    icon: 6,
                    signature: 7,
                }
                const arr = []
                this.optionWriteList.forEach(item => {
                    arr.push(viewProjectObj[item.key])
                })
                return arr.join(',')
            }
            return ''
        },
        getDefaultTxt() {
            // console.log('this.selectOption.custom.list', this.selectOption.custom.list)
            const text = this.selectOption.custom.list.join('|')
            // console.log('text', text)
            return text
        },
        // 获取要上传服务器的内容
        getSaveData() {
            return {
                TplNo: this.queryStr.no,
                SetType: this.selectOptionActive === 'normal' ? 1 : 2,
                ViewProject: this.getViewProject(),
                DefaultTxt: this.getDefaultTxt(),
            }
        },
        // 保存名片数据到服务器
        saveCardCloud() {
            const requestData = this.getSaveData()
            console.log('requestData', requestData)
            setBusCardTemp(requestData)
            .then(res => {
                console.log('设置用户名片默认模板 res：', res)
                if (res.errcode == 0) {
                    
                } else {
                    if (res.errcode != -2 && res.errCode != 1100) {
                        // failTextVantToa()
                    } else {
                        // clearVantToa()
                    }
                }
            }, res => {
                console.log('设置用户名片默认模板fail: res', res)
                if (res.errcode != 2000) {
                    // failTextVantToa()
                }
            })
            .catch(res => {
                console.log('设置用户名片默认模板catch：res', res)
                // failTextVantToa()
            })
        },
        // 执行生成名片
        saveCard() {
            if (isLoginChose()) {
                this.saveCardCloud()
                this.$refs.cardDom.saveCard()
            }
        },
        setTempData() {
            let data = sessionStorage.getItem('WriteBusCardWriteData')
            if (data) {
                data = JSON.parse(data)
                // console.log('cache selectedData', data)
                this.selectedData = data
                // if (Array.isArray(data.customTxtItem) && data.customTxtItem.length > 0) {
                //     this.setTempCusData(data.customTxtItem)
                // }
                if (data.tplImgUrl) {
                    this.userInfo.tempImg = data.tplImgUrl
                }
                if (data.setType == 2) {
                    this.selectOptionActive = 'custom'
                    this.showDomContentType = 'custom'
                } else {
                    this.selectOptionActive = 'normal'
                    this.showDomContentType = 'normal'
                }
            }
        },
        setSelctOption(id) {
            // console.log('setSelctOption id', id)
            if(id) {
                this.selectOptionActive = id
                this.showDomContentType = id
            }
        },
        addOption({name, val, arr, key}) {
            // console.log(`val: ${val}, name: ${name}`)
			if (name && val && Array.isArray(arr)) {
				// console.log('push')
				arr.push({ 
                    name, 
                    val,
                    isShow: true,
                    key
                })
			}
        },
        setWriteOptionList() {
            const arr =[]
            // console.log('this.selectedData.viewProject', this.selectedData.viewProject)
            const arrShow = this.selectedData.viewProject ? this.selectedData.viewProject.split(',') : true
            this.addOption({
                name: '标志', 
                val: '标志', 
                arr, 
                key: 'icon', 
                isShow: Array.isArray(arrShow) ? arrShow.indexOf(6) : arrShow
            })
            this.addOption({
                name: '签名', 
                val: getText(this.userInfo.signature), 
                arr, 
                key: 'signature',
                isShow: Array.isArray(arrShow) ? arrShow.indexOf(7) : arrShow,
            })
            this.addOption({
                name: '位置', 
                val: getText(this.userInfo.area), 
                arr, 
                key: 'area',
                isShow: Array.isArray(arrShow) ? arrShow.indexOf(1) : arrShow
            })
			this.addOption({
                name: '公司', 
                val: getText(this.userInfo.companyName), 
                arr, 
                key: 'company',
                isShow: Array.isArray(arrShow) ? arrShow.indexOf(2) : arrShow
            })
			this.addOption({
                name: '介绍', 
                val: getText(this.userInfo.yourSelf), 
                arr, 
                key: 'presentation',
                isShow: Array.isArray(arrShow) ? arrShow.indexOf(3) : arrShow
            })
			this.addOption({
                name: '供应', 
                val: getText(this.userInfo.supply), 
                arr, 
                key: 'supply',
                isShow: Array.isArray(arrShow) ? arrShow.indexOf(4) : arrShow
            })
            this.addOption({
                name: '需求', 
                val: getText(this.userInfo.demand), 
                arr, 
                key: 'demand',
                isShow: Array.isArray(arrShow) ? arrShow.indexOf(5) : arrShow
            })
            this.optionWriteList = arr
            // console.log('this.optionWriteList', this.optionWriteList)
        },
        setIsShow({key, index}) {
            const arr = this.optionWriteList
            for(let i = 0; i < arr.length; i++){
                if (arr[i].key == key) {
                    const obj = Object.assign({}, arr[i])
                    obj.isShow = !obj.isShow
                    arr.splice(i, 1, obj)
                    break
                }
            }
        },
        changeCustomText(inputText) {
            if (typeof inputText === 'object') {
                const that = this
                that.selectOption.custom.list = []
                Object.keys(inputText).forEach((item, index) => {
                    // console.log('item', item)
                    that.selectOption.custom.list.push(inputText[index] || '')
                })
            }
        }
    },
    // mounted() {
        
    // },
    activated() {
        this.getUserBus() // 获取用的名片信息
        this.setTempData() // 设置模板内容信息
        const that = this
        if (that.$store.getters.isWechatBro) {
			checkDataEqualVal({
				data: that.$store.getters,
				key: 'getWechatStatus',
				val: ['success', 'fail'],
				callback(val) {
					if (val === 'success') {
                        defaultShare({})
                    }
				}
			})
        }
        this.queryStr = getQueryStrParams({
            params: ["type", "no"],
            query: this.$route.query
        })
    },
    components: {
        TopNav,
        CardDom,
        SelecOption,
        BtnMenu,
    }
}
</script>

<style lang="scss" scoped>
.card-dom {
    padding: 15px 0;
}
</style>